package tl_model

import (
	"database/sql"
	"log"
	"os"
	"path/filepath"
	"sync"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	// replace cgo
	_ "modernc.org/sqlite"

	_ "modernc.org/sqlite"
)

var (
	once sync.Once
	db   *gorm.DB
)

func GetDB() *gorm.DB {
	once.Do(func() {
		db = initDB()
	})
	return db
}

func initDB() *gorm.DB {
	dbDir := os.Getenv("DB_DIR")
	if dbDir == "" {
		os.Setenv("dbDir", "/root/")
		dbDir = os.Getenv("dbDir")
	}
	if !filepath.IsAbs(dbDir) {
		log.Panicf("dbDir must be abs: %s", dbDir)
	}
	log.Printf("dbDir: %s", dbDir)
	db_path := filepath.Join(dbDir, "test_loss.db")

	// _db, err := gorm.Open(sqlite.Open(db_path), &gorm.Config{})

	sqlDb, err := sql.Open("sqlite", db_path)
	if err != nil {
		log.Panicf("sql.Open failed to connect database: %v", err)
	}

	_db, err := gorm.Open(sqlite.Dialector{Conn: sqlDb}, &gorm.Config{})
	if err != nil {
		log.Panicf("gorm.Open failed to connect database: %v", err)
	}
	_db.AutoMigrate(&JobInfo{})
	err = _db.AutoMigrate(&JobInfo{})
	if err != nil {
		log.Panicf("Failed to migrate database: %v", err)
	}
	return _db
}
